package interaction;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import loadsave.LoadSaveable;
import loadsave.Memento;
import loadsave.loadsaveobject.Iterator;
import loadsave.loadsaveobject.LoadSaveCollectionComposite;
import loadsave.loadsaveobject.LoadSaveIndex;
import loadsave.loadsaveobject.LoadSaveObject;
import loadsave.loadsaveobject.LoadSaveObjectComposite;
import model.MessageSpooler;

public class InteractionOption implements LoadSaveable {

	private ArrayList<InteractionCommand> commandList;
	private String msg;
	
	public InteractionOption(String msg) {
		commandList = new ArrayList<InteractionCommand>();
		this.msg = msg;
	}
	
	/**
	 * add a given command to the list
	 * @param command
	 * @return
	 */
	public boolean addIntCommand(InteractionCommand command) {
		return commandList.add(command);
	}
	
	/**
	 * remove a command from the list
	 * @param command
	 * @return
	 */
	public InteractionCommand removeIntCommand(InteractionCommand command) {
		int index = commandList.indexOf(command);
		return commandList.remove(index);
	}
	
	/**
	 * set the overall message
	 * @param s
	 */
	public void setMessage(String s) {
		msg = s;
	}
	
	/**
	 * spool the message in the message spooler
	 * @param at
	 */
	public void execute(int at) {
		MessageSpooler.getInstance().addMessage(msg);
	    commandList.get(at).execute();
	}
	
	/**
	 * get an iterator for the list of commands
	 * @return
	 */
	public java.util.Iterator<InteractionCommand> iterator() {
		return (commandList.iterator());
	}

	@Override
	public Memento getMemento() {
		return new Memento() {

			@Override
			public LoadSaveObject getState() {
				LoadSaveObjectComposite toReturn = new LoadSaveObjectComposite("", "InteractionOption");
				LoadSaveCollectionComposite lscc = new LoadSaveCollectionComposite("commandList", "ArrayList", "InteractionCommand");
				int index = 0;
				for (InteractionCommand ic : commandList) {
					lscc.add(new LoadSaveIndex(++index), ic.getMemento().getState());
				}
				toReturn.add(lscc.getName(), lscc);
				return toReturn;
			}

			@Override
			public void restoreState(LoadSaveObject lso) {
				Iterator<LoadSaveObject> i = lso.get("commandList").getIterator();
				for (i.init(); i.hasNext(); i.next()) {
					Map<String, InteractionCommand> ICTypes = new HashMap<String, InteractionCommand>();
					ICTypes.put("AttackIC", new AttackIC());
					ICTypes.put("ShopIC", new ShopIC());
					ICTypes.put("UseItemIC", new UseItemIC());
					ICTypes.put("UseSkillIC", new UseSkillIC());
					InteractionCommand ic = ICTypes.get(i.getCurrVal().getType()).clone();
					ic.getMemento().restoreState(i.getCurrVal());
				}
			}
			
		};
	}

}
